<template>
    <div class="tag-selector card">
        <div class="section existing-tags">
            <h3><i class="icon-tag me-2"></i>选择文章标签</h3>
            <div class="tags-container">
                <div v-for="tag in availableTags" :key="tag.id" class="tag-option d-flex align-items-center mb-2">
                    <input type="checkbox" :id="'tag-' + tag.id" :value="tag.id" v-model="selectedTagIds">
                    <label :for="'tag-' + tag.id" class="ms-2 flex-1">{{ tag.name }}</label>
                </div>
            </div>
        </div>

        <div class="section new-tag">
            <h3><i class="icon-plus-circle me-2"></i>或创建新标签</h3>
            <div class="input-group">
                <input type="text" v-model="newTag" placeholder="输入新标签名称" @keyup.enter="addNewTag">
                <button class="btn-add" @click="addNewTag">添加</button>
            </div>
        </div>

        <div class="section selected-tags" v-if="selectedTags.length > 0">
            <h3><i class="icon-check-circle me-2"></i>已选标签：</h3>
            <div class="tag-list">
                <span v-for="tagId in selectedTags" :key="tagId" class="tag-badge">
                    {{ getTagName(tagId) }}
                    <button @click="removeTag(tagId)" class="remove-tag">×</button>
                </span>
            </div>
        </div>

        <div class="action-buttons">
            <button class="btn-primary" @click="confirmSelection">下一步 →</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '@/http'
import { useRouter } from 'vue-router'
const availableTags = ref([])
const selectedTagIds = ref([])
const newTag = ref('')
const selectedTags = ref([])
let router = useRouter()

// 获取标签数据
const fetchTags = async () => {
    try {
        const response = await http.get('/tag/')
        availableTags.value = response.data.data.map(tag => ({
            id: tag.id,
            name: tag.name
        }))
    } catch (error) {
        console.error('获取标签失败:', error)
        alert('加载标签失败，请刷新页面')
    }
}

// 添加新标签
const addNewTag = async () => {
    const tagName = newTag.value.trim()
    if (!tagName) return

    const exists = availableTags.value.some(tag => tag.name === tagName)
    if (exists) {
        const tag = availableTags.value.find(tag => tag.name === tagName)
        if (!selectedTagIds.value.includes(tag.id)) {
            selectedTagIds.value.push(tag.id)
        }
    } else {
        try {
            const response = await http.post('/tag/', { name: tagName })
            const newTagObj = { id: response.data.data.id, name: tagName }
            availableTags.value.push(newTagObj)
            selectedTagIds.value.push(newTagObj.id)
        } catch (error) {
            console.error('创建标签失败:', error)
            alert('创建标签失败，请重试')
        }
    }
    newTag.value = ''
}

// 移除已选标签
const removeTag = (tagId) => {
    selectedTagIds.value = selectedTagIds.value.filter(id => id !== tagId)
}

// 获取标签名称
const getTagName = (tagId) => {
    const tag = availableTags.value.find(t => t.id === tagId)
    return tag ? tag.name : '未知标签'
}

// 确认选择并传递给父组件 + 路由传参
const confirmSelection = () => {
    // 组装要传递的标签数据，这里简单处理成带名称和id的数组
    const tagData = selectedTagIds.value.map(id => ({
        id,
        name: getTagName(id)
    }))
    // 通过路由 query 传参，将标签数据转成 JSON 字符串（因为 query 一般传字符串）
    const queryParams = {
        tags: JSON.stringify(tagData)
    }
    router.push({
        path: '/text',
        query: queryParams
    })
    // 也可以继续触发自定义事件给父组件，看实际需求
    emit('select-tags', tagData)
}

const emit = defineEmits(['select-tags'])

onMounted(() => {
    fetchTags()
})
</script>

<style scoped>
/* 全局样式变量，统一基础配色 */
:root {
    --primary-color: #409eff;
    /* 主色，类似 Element UI 风格 */
    --border-color: #dcdcdc;
    /* 边框色 */
    --text-color: #303133;
    /* 文字主色 */
    --tag-bg: #f0f2f5;
    /* 标签背景色 */
    --error-red: #f56c6c;
    /* 错误红 */
}

.tag-selector {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin: 16px 0;
    /* 增加外间距，避免贴边 */
}

.section {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
}

.section:last-child {
    border-bottom: none;
}

h3 {
    margin: 0 0 12px;
    font-size: 16px;
    color: var(--text-color);
    display: flex;
    align-items: center;
    font-weight: 500;
    /* 加粗标题 */
}

/* 图标样式 */
.icon-tag,
.icon-plus-circle,
.icon-check-circle {
    margin-right: 8px;
    font-size: 18px;
    color: #666;
}

/* 现有标签区域 */
.tags-container {
    max-height: 200px;
    overflow-y: auto;
}

.tag-option {
    cursor: pointer;
    transition: background-color 0.2s ease;
    /* 增加背景过渡 */
    padding: 4px 0;
    /* 增加内间距，点击更舒适 */
}

.tag-option:hover {
    background-color: #f8f9fa;
    /*  hover 背景色 */
}

.tag-option:hover label {
    text-decoration: underline;
}

/* 输入框组 */
.input-group {
    display: flex;
    gap: 8px;
    align-items: center;
}

.input-group input {
    flex: 1;
    padding: 8px 12px;
    /* 调整内间距 */
    border: 1px solid var(--border-color);
    border-radius: 4px;
    /* 统一圆角 */
    transition: border-color 0.2s ease;
}

.input-group input:focus {
    outline: none;
    border-color: var(--primary-color);
    /* 聚焦高亮 */
}

.btn-add {
    padding: 8px 16px;
    /* 调整内间距 */
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 4px;
    /* 统一圆角 */
    cursor: pointer;
    transition: background 0.2s;
}

.btn-add:hover {
    background: #66b1ff;
    /* 主色 hover 加深 */
}

/* 已选标签区域 */
.tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.tag-badge {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    /* 调整内间距 */
    background: var(--tag-bg);
    border-radius: 16px;
    font-size: 14px;
    color: #333;
    border: 1px solid rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
    /* 增加过渡 */
}

.tag-badge:hover {
    transform: scale(1.02);
    /* 轻微缩放 */
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    /* 增加阴影 */
}

.remove-tag {
    margin-left: 8px;
    background: none;
    border: none;
    color: #999;
    font-size: 16px;
    /* 调整大小 */
    cursor: pointer;
    transition: color 0.2s;
    line-height: 1;
    /* 垂直居中 */
}

.remove-tag:hover {
    color: var(--error-red);
}

/* 响应式适配 */
@media (max-width: 768px) {

    .icon-tag,
    .icon-plus-circle,
    .icon-check-circle {
        font-size: 16px;
    }

    .input-group {
        flex-direction: column;
        gap: 8px;
        /* 调整间距 */
    }

    .input-group input {
        border-radius: 4px;
        margin-bottom: 0;
        /* 还原 margin */
        width: 100%;
        /* 占满宽度 */
    }

    .btn-add {
        border-radius: 4px;
        width: auto;
        align-self: flex-start;
        /* 左对齐 */
    }
}
</style>